package com.hy.service.impl;

import com.hy.entitys.Chapter;
import com.hy.entitys.StoryEntity;
import com.hy.entitys.WebStorageEntity;
import com.hy.mapper.StoryMapper;
import com.hy.service.IStoryService;

import com.hy.service.StoryService;
import com.hy.service.WebStorageService;
import com.hy.utils.StoryUtils;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
public class StoryServiceImp implements IStoryService {
    //注入网站仓库服务
   @Autowired
   public WebStorageService webStorageService;

    @Autowired
   public StoryService storyService;
    //声明小说工具对象
    private final StoryUtils storyUtils = new StoryUtils();

    @Override
    public List<Chapter> getChapters(String url, Integer webStorageId) {
        //该网站对应的选择器
       WebStorageEntity web = webStorageService.getById(webStorageId);
       return  storyUtils.getChapter(url, web.getChapterSelect());
    }

    @Override
    public List<StoryEntity> findStory(String name) {
        List<StoryEntity> storyEntities = new ArrayList<>();
        List<WebStorageEntity> list = webStorageService.list();
        list.forEach(web -> {
            if (web.getFindUrl()!=null){
                HashMap<String, Object> params = new HashMap<>();
                params.put("siteid","bixiaorg");
                params.put("q",name);
                String url=web.getFindUrl();
                String select= web.getFindSelect();
                Elements crawl = storyUtils.crawl(url,select,params);

                crawl.forEach(element -> {
                    StoryEntity storyEntity = new StoryEntity();
                    if (element.child(1)!=null){
                        storyEntity.setAuthor(element.child(1).select(".s4").text());
                        storyEntity.setName(element.child(1).select(".s2 a").text());
                        storyEntity.setChapterUrl(element.child(1).select(".s2 a").attr("href"));
                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        storyEntity.setUpdateTime(LocalDateTime.parse(element.child(1).select(".s6").text(),df));
                        storyEntity.setWebStorageId(web.getId());
                        storyEntity.setStatus(0);
                        storyEntities.add(storyEntity);
                    }

                });
            }
        });

        return storyEntities;
    }

    @Override
    public String saveStoryAll(List<StoryEntity> storys) {

        return null;
    }
}
